package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.pojo.TodoVO;
import com.itheima.service.TodoService;
import com.itheima.dao.TodoMapper;
import com.itheima.pojo.Todo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;

@Service
public class TodoServiceImpl implements TodoService {

    @Autowired
    private TodoMapper todoMapper;

    /**
     * 添加
     * @param todoVO
     */
    @Override
    public void add(TodoVO todoVO) {
        Todo todo = JSON.parseObject(JSON.toJSONString(todoVO), Todo.class);
        //生成uid
        String uid = UUID.randomUUID().toString().replace("-","");
        todo.setUid(uid);
        todoMapper.insertSelective(todo);
    }

    /**
     * 删除
     * @param todoVO
     */
    @Override
    public void delete(TodoVO todoVO) {
        Example example = createExample(todoVO);
        todoMapper.deleteByExample(example);
    }

    /**
     * 编辑
     * @param todoVO
     */
    @Override
    public void edit(TodoVO todoVO) {
        Todo todo = JSON.parseObject(JSON.toJSONString(todoVO), Todo.class);
        Example example = new Example(Todo.class);
        Example.Criteria criteria = example.createCriteria();
        if (todo.getUid() != null){
            criteria.andEqualTo("uid",todo.getUid());
        }
        todoMapper.updateByExample(todo,example);
    }

    /**
     * 条件+分页查询
     * @param todoVO
     * @return
     */
    @Override
    public PageInfo getList(TodoVO todoVO) {
        Integer currentPage = todoVO.getCurrentPage();
        Integer pageSize = todoVO.getPageSize();
        //查询所有数据
        Example example = createExample(todoVO);
        List<Todo> todos = todoMapper.selectByExample(example);
        //分页
        PageHelper.startPage(currentPage,pageSize);
       return new PageInfo<>(todos);
    }

    private Example createExample(TodoVO todoVO){
        Example example=new Example(Todo.class);
        Example.Criteria criteria = example.createCriteria();
        if(todoVO!=null) {
            // 事项是否完成
            if (todoVO.getDone() != null && !"".equals(todoVO.getDone())) {
                criteria.andEqualTo("done", todoVO.getDone());
            }
            // 状态
            if (todoVO.getStatus() != null && !"".equals(todoVO.getStatus())) {
                criteria.andEqualTo("status", todoVO.getStatus());
            }
            // 评论类型
            if (todoVO.getUid() != null && !"".equals(todoVO.getUid())) {
                criteria.andEqualTo("uid", todoVO.getUid());
            }
            // 用户uid
            if (todoVO.getText() != null && !"".equals(todoVO.getText())) {
                criteria.andEqualTo("text", todoVO.getText());
            }
        }
        return example;
    }
}
